<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-03 00:33:05
 * @LastEditTime: 2023-09-22 14:37:55
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Models;

use App\Repositories\FinanceVoucherRepository;
use App\Traits\AttachmentTrait;
use App\Traits\AutoCodeTrait;
use App\Traits\VoucherTrait;

class FinanceTransfer extends BaseModel
    {
    use AutoCodeTrait;
    use AttachmentTrait;
    use VoucherTrait;
    public $timestamps = true;
    public $table = "sys_finance_transfer";
    protected $guarded = [];

    protected $casts = [];
    // FINANCE_TRANSFER
    /**
     * 标识
     *
     * @var string
     */
    protected $ACSign = 'FINANCE_TRANSFER';
    public function in_subject()
        {
        return $this->belongsTo(Subject::class);
        }

    public function status()
        {
        return $this->belongsTo(Dic::class, "status_id", "key")->where(function ($q)
            {
            $q->where("code", 'status_with_finance');
            });
        }
    public function out_subject()
        {
        return $this->belongsTo(Subject::class);
        }
    public function in_currency()
        {
        return $this->belongsTo(Currency::class);
        }
    public function out_currency()
        {
        return $this->belongsTo(Currency::class);
        }

    public function finance($orders = null)
        {
        $v = $orders ?? $this;
        if ($v->status_id == 2)
            return $v->voucher;
        if ($v->status_id != 1) {
            fail("单据非审核状态！，无法财审！");
            }
        $details = [];

        $summary = $v->out_subject->name . " 转账 " . $v->in_subject->name . "  " . ($v->summary ?? "");

        //借 银行存款
        $details[] = FinanceVoucherRepository::mergeVoucher($v->in_subject_id, $summary, $v->in_amount, 0, $v->toArray());
        //贷 银行存款
        $details[] = FinanceVoucherRepository::mergeVoucher($v->out_subject_id, $summary, 0, $v->out_amount, $v->toArray());

        $voucher = FinanceVoucherRepository::CreateVoucher($v->billdate, 1, $details, $v, $v->voucher?->id);

        //审核凭证
        fauditSave($v);
        return FinanceVoucherRepository::auditVoucher($voucher);
        }

    }
